import React, { Component } from 'react';
import { GLOBAL } from '../../../config/global';
import { NavigationEvents } from 'react-navigation';
import { StyleSheet, Text, View, Image, TouchableOpacity, PixelRatio, FlatList, Alert, TextInput, Animated } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import Dictionary from '../../../utils/dictionary';
import { RangTime } from '../../../component/common/RangTime.js';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import moment from 'moment';
import serviceAPI from './_common/serviceAPI';
import { ResourceToClaimCpt } from './_components/ResourceToClaimCpt';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
const scale = GLOBAL.SCALE;

export class ToClaimList extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: '意向认领列表',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: <Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />,
      headerStyle: {
        elevation: 0,
        backgroundColor: style.color.themeColor,
        borderBottomWidth: 0
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  }

  constructor(props) {
    super(props);
    let { choice, searchKey, beginDate, endDate, longFrame, isNoClaimFlag, isCanClaimFlag, isClaimedFlag } = props.navigation.state.params || {};
    if (props.navigation.state.params && !props.navigation.state.params.hasOwnProperty('isCanClaimFlag')) isCanClaimFlag = '1'; //默认选中 近看未认领
    this.state = {
      status: 'data',
      listData: [],
      refreshIcon: false,
      showTimeModal: false, // 时间选择
      alertShow: false,
      options: [],
      choice: choice || {},
      tabIndex: 0,
    };
    this.totalPage = 1;
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.selectedFrame = longFrame || {};
    this.pageParams = {
      searchKey: searchKey || null,
      beginDate: null, //开始时间
      endDate: null, //结束时间
      areaId: null, //状态 
      pageNo: 1,
      pageSize: 10,
      isNoClaimFlag: isNoClaimFlag || null, // 仅看未认领
      isCanClaimFlag: isCanClaimFlag || null, //仅看自己可认领
      isClaimedFlag: isClaimedFlag || null, //仅看已认领
    }
    this.userId = null; // 用户id

    this.dateObj = {
      startDate: moment(moment().subtract(1, 'months').calendar()).format('YYYY-MM-DD') || null,
      endDate: moment().format('YYYY-MM-DD') || null
    };
    if (typeof beginDate != 'undefined') {
      this.dateObj.startDate = null;
    }
    if (typeof endDate != 'undefined') {
      this.dateObj.endDate = null;
    }
  }

  async componentWillMount() {
    await this._getUserId();
    await this._initPage();
  }


  _getNum = async () => {
    this._getSend();
    let res = null;
    res = await serviceAPI.claimNum(this.pageParams || {});
    if (res) {
      this.recordCountBuy = res.purchaceBidCnt;
      this.recordCount = res.saleBidCnt;
    }
  }

  _getSend = () => {
    let { tabIndex } = this.state || {};
    this.pageParams.beginDate = this.dateObj.startDate;
    this.pageParams.endDate = this.dateObj.endDate;
    this.pageParams.areaId = null;
    this.pageParams.searchKey = this.pageParams.searchKey == '' ? null : this.pageParams.searchKey;
    this.pageParams.orderType = tabIndex ? 'P' : 'S';
    this.pageParams.corpId = this.state.choice.corpId;
  }

  _initPage = async () => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this._getSend();


    await this._getNum();

    let res = null;
    res = await serviceAPI.claimList(this.pageParams || {});
    console.log('页面获取-参数', this.pageParams);
    console.log('页面获取-res', res)
    if (res && res.rows) {
      this._extendData(res.rows);
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false,
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  //extend 数据
  _extendData = (arrData) => {
    let { tabIndex } = this.state || {};
    arrData && arrData.map((item, index) => {
      item.userId = this.userId;
      item.index = index;
      item.resourceBidOrderList && item.resourceBidOrderList.forEach(element => {
        element.checked = false;
      });
      if (tabIndex) {
        item.orderType = 'P';
      } else {
        item.orderType = 'S';
      }
    })
  }

  // 获取用户id
  _getUserId = async () => {
    let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      this.userId = userInfo.userId;
      this.bizRegion = userInfo.bizRegion || false;
      this.setState({
        options: userInfo.corpInfoTOs || [],
        choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
      })
    }
  }


  // 下拉刷新
  _refresh = () => {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this._initPage();
  }

  // 刷新
  _reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this._initPage();
  }

  // 加载更多
  _loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this._initPage();
    }
  }

  // 搜索View
  _renderSearchWarp = () => {
    const searchIcon = require('../../../imgs/global/whiteSearch.png');
    return (
      <View style={styles.filterWrap}>
        <View>
          <Image source={searchIcon} style={styles.searchIcon} />
          <TextInput
            ref="orderKeywordsInput"
            style={styles.searchInput}
            underlineColorAndroid='transparent'
            placeholder={"商品名称/资源包编号/企业"}
            placeholderTextColor="rgba(255, 255, 255, .8)"
            maxLength={30}
            returnKeyType={'search'}
            defaultValue={this.pageParams.searchKey}
            onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
            onSubmitEditing={() => { this._refresh() }}
          />
        </View>
      </View>
    )
  }

  _callback = (data) => {
    console.log('返回数据', data)
    let { listData } = this.state || {};
    listData[data.index] = data;
    this.setState({
      listData
    }, () => {
      console.log('listData-123', listData)
    })
  }

  _renderListItem = (data) => {
    return <ResourceToClaimCpt itemData={data.item || {}} choice={this.state.choice} callback={this._callback} />
  }

  //打开时间弹框
  _timeOpen = () => {
    this.setState({
      showTimeModal: true
    })
  }

  // 选择时间
  _resultCall = (resultData) => {
    this.dateObj.startDate = resultData.startTime || '';
    this.dateObj.endDate = resultData.endTime;
    this.setState({ showTimeModal: false, }, () => {
      this._refresh();
    })
  }

  //勾选
  _boxFn = (checkString) => {
    //清空之前的
    this.pageParams.isNoClaimFlag = null;
    this.pageParams.isCanClaimFlag = null;
    this.pageParams.isClaimedFlag = null;
    this.pageParams[checkString] = '1';
    this._reloadPage();
  }

  //tab切换
  _tabFn = (index) => {
    let { tabIndex } = this.state;
    this.setState({
      tabIndex: index
    }, () => {
      this._reloadPage();
    })
  }

  render() {
    let { status, listData, refreshIcon, showTimeModal, tabIndex,
      alertShow, choice, options } = this.state || {};
    let { isNoClaimFlag, isCanClaimFlag, isClaimedFlag } = this.pageParams || {};
    const correct = require('../../../imgs/global/correct.png');
    return (
      <View style={styles.container}>
        <NavigationEvents
          onWillFocus={async ({ action }) => {
            await this._getUserId();
            await this._reloadPage();
          }}
        />
        <View style={styles.headBox}>
          <View style={{ flexDirection: 'row', paddingLeft: 20 * scale, justifyContent: 'space-between', alignItems: 'center' }}>
            <View style={styles.searchBox}>
              {this._renderSearchWarp()}
            </View>
            <View style={{ marginRight: 10 * scale }}>
              {options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
            </View>
          </View>
          <View style={styles.headTab}>
            <TouchableOpacity onPress={() => { this._tabFn(0) }} style={[styles.tabItem, tabIndex == 0 ? styles.tabActive : null]}>
              <Text style={[styles.tabText]}>销售意向</Text>
              <Text style={styles.hdInfo}>{this.recordCount}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => { this._tabFn(1) }} style={[styles.tabItem, tabIndex == 1 ? styles.tabActive : null]}>
              <Text style={[styles.tabText]}>采购意向</Text>
              <Text style={styles.hdInfo}>{this.recordCountBuy || 0}</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.statusBox}>
          <View style={{ flexDirection: 'row', width: 200 * scale, flexWrap: 'wrap' }}>
            <TouchableOpacity onPress={() => { this._boxFn('isNoClaimFlag') }} style={[styles.hdBox, { marginBottom: 5 * scale }]}>
              <View style={styles.lockView} >
                {isNoClaimFlag ? <Image style={styles.lockImage} source={correct} /> : null}
              </View>
              <Text style={styles.hdLookText}>仅看未认领</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => { this._boxFn('isCanClaimFlag') }} style={[styles.hdBox, { marginBottom: 5 * scale }]}>
              <View style={styles.lockView} >
                {isCanClaimFlag ? <Image style={styles.lockImage} source={correct} /> : null}
              </View>
              <Text style={styles.hdLookText}>仅看自己可认领</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => { this._boxFn('isClaimedFlag') }} style={styles.hdBox}>
              <View style={styles.lockView} >
                {isClaimedFlag ? <Image style={styles.lockImage} source={correct} /> : null}
              </View>
              <Text style={styles.hdLookText}>仅看已认领</Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity style={styles.statusItem} onPress={this._timeOpen}>
            <View style={{ flexDirection: 'row' }}>
              <Image style={styles.statusTimeImg} source={require('../../../imgs/time.png')}></Image>
            </View>
            <View>
              <Text style={styles.statusItemText}>{this.dateObj.startDate || ''}</Text>
              <Text style={styles.statusItemText}>{this.dateObj.endDate || ''}</Text>
            </View>
            <View style={{ flexDirection: 'row' }}>
              <Text style={[styles.statusItemText, styles.statusItemTextActive]}>至</Text>
            </View>
          </TouchableOpacity>
        </View>
        {
          status == 'data' ? (
            <View style={{ flex: 1 }}>
              <View style={{ marginTop: 10 * scale }}>
                <FlatList
                  data={listData}
                  renderItem={this._renderListItem}
                  refreshing={refreshIcon}
                  onRefresh={() => { this._refresh() }}
                  onEndReachedThreshold={0.1}
                  onEndReached={() => { this._loadMore() }}
                />
              </View>
            </View>
          ) : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无数据" onErrorPress={this._reloadPage} />) : null
        }
        {/* 时间弹框 */}
        {
          showTimeModal ? <RangTime isClear={true} isVisible={true} markedDates={null} startTime={this.dateObj.startDate} endTime={this.dateObj.endDate} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
        }
        <SlideSelect alertShow={alertShow} options={options}
          select={(val) => {
            this.setState({ choice: val || options[0], alertShow: false }, () => {
              this._reloadPage();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />

      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    position: 'relative'
  },
  headBox: {
    height: 115 * scale,
    backgroundColor: style.color.themeColor,
  },
  searchBox: {
    width: 230 * scale
  },
  statusBox: {
    height: 48 * scale,
    width: 351 * scale,
    borderRadius: 5 * scale,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingLeft: 5 * scale,
    paddingRight: 5 * scale,
    marginLeft: 12 * scale,
    marginTop: 5 * scale,
    marginBottom: 10 * scale,
  },
  statusItem: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 120 * scale,
  },
  statusItemText: {
    fontSize: 11 * scale,
    color: style.color.themeColor,
    marginBottom: 3 * scale
  },
  statusItemTextActive: {
    paddingLeft: 3 * scale,
    paddingRight: 2 * scale
  },
  searchWrap: {
    width: '100%',
    height: 66 * scale,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  btnWarp: {
    height: 72 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  searchInput: {
    height: 36 * scale,
    width: 220 * scale,
    paddingLeft: 50 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#fff',
  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 15 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  filterWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: style.color.themeColor,
    paddingTop: 14 * scale,
    paddingBottom: 14 * scale,
  },
  radio: {
    marginTop: 7 * scale
  },
  hdBox: {
    flexDirection: 'row',
    alignItems: 'center',
    //paddingLeft: 15 * scale,
    paddingRight: 15 * scale,
    marginTop: 8 * scale
  },
  hdLookText: {
    color: style.color.themeColor,
    fontSize: 10 * scale,
  },
  headTab: {
    width: '100%',
    height: 40 * scale,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  tabText: {
    color: '#fff',
    fontSize: 14 * scale,
    marginBottom: 12 * scale
  },
  tabActive: {
    borderBottomWidth: 2 * scale,
    borderStyle: 'solid',
    borderBottomColor: style.color.white,
    paddingLeft: 5 * scale,
    paddingRight: 5 * scale
  },
  tabItem: {
    flexDirection: 'row',
    borderBottomWidth: 2 * scale,
    borderStyle: 'solid',
    borderBottomColor: style.color.themeColor,
    paddingLeft: 5 * scale,
    paddingRight: 5 * scale
  },
  hdInfo: {
    color: '#fff',
    paddingLeft: 5 * scale,
    fontSize: 14 * scale
  },
  statusTimeImg: {
    tintColor: style.color.themeColor,
    marginRight: 5 * scale,
    width: 18 * scale,
    height: 22 * scale
  },
  lockView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: style.color.themeColor,
    marginRight: 10 * scale,
  },
  lockImage: {
    tintColor: style.color.themeColor,
    width: 8 * scale,
    height: 8 * scale
  }
})